package com.ruoyi.dynamic.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.CacheKey;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.redis.cache.CacheTemplate;
import com.ruoyi.dynamic.mapper.RoomHeartMapper;
import com.ruoyi.dynamic.model.constant.DynamicConstant;
import com.ruoyi.dynamic.model.constant.ParamConstant;
import com.ruoyi.dynamic.model.constant.RoomChatRoomKvConstant;
import com.ruoyi.dynamic.model.pojo.entity.Room;
import com.ruoyi.dynamic.model.pojo.entity.RoomHeart;
import com.ruoyi.dynamic.model.pojo.entity.RoomHeartRecord;
import com.ruoyi.dynamic.model.pojo.entity.RoomType;
import com.ruoyi.dynamic.model.pojo.request.app.*;
import com.ruoyi.dynamic.model.pojo.result.app.*;
import com.ruoyi.dynamic.service.*;
import com.ruoyi.system.api.RemoteAppUserService;
import com.ruoyi.system.api.model.user.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 房间心动交友记录 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-12-16
 */
@Service
public class RoomHeartServiceImpl extends ServiceImpl<RoomHeartMapper, RoomHeart> implements IRoomHeartService {

    @Autowired
    private IRoomService iRoomService;
    @Autowired
    private IRoomTypeService iRoomTypeService;
    @Autowired
    private IRoomHeartRecordService iRoomHeartRecordService;
    @Autowired
    private RemoteAppUserService remoteAppUserService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IParamService iParamService;

    @Override
    public Long openGame(AppRoomHeartCreateRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        Assert.isTrue(verify.getRoomTypeId().equals(DynamicConstant.RoomType.Heart), "此房间模式不是心动交友模式");
        Assert.isTrue(verify.getUserId().equals(userId), "您不是房主无法开启游戏");
        RoomType roomType = iRoomTypeService.verify(verify.getRoomTypeId());
        List<AppRoomMaiUserResult> appRoomMaiUserResults = iRoomService.maiUsers(request.getRoomId(), DynamicConstant.MaiType.MAI, false, true, 0L, 0);
        Assert.notEmpty(appRoomMaiUserResults, "房间无上麦人员无法开启交友游戏");
        Assert.isTrue(appRoomMaiUserResults.size() >= roomType.getMinNum(), "用户低于最少开启" + roomType.getMinNum() + "人数");
        Long count = lambdaQuery()
                .eq(RoomHeart::getRoomId, request.getRoomId())
                .eq(RoomHeart::getStatus, DynamicConstant.CheckStatus.YES)
                .count();
        Assert.isTrue(count == 0, "还有未结束的 无法开启");

        RoomHeart roomHeart = new RoomHeart();
        roomHeart.setRoomId(request.getRoomId());
        roomHeart.setUserId(userId);
        roomHeart.setContent(request.getContent());
        roomHeart.setStatus(DynamicConstant.CheckStatus.YES);
        roomHeart.setCreateTime(new Date());
        if (save(roomHeart)) {
            List<RoomHeartRecord> list = appRoomMaiUserResults.stream()
                    .map(res -> {
                        RoomHeartRecord record = new RoomHeartRecord();
                        record.setUserId(res.getId());
                        record.setMaiNum(res.getMaiNum());
                        record.setContent(request.getContent());
                        record.setRoomId(verify.getId());
                        record.setRoomHeartId(roomHeart.getId());
                        record.setUserName(res.getNickName());
                        record.setUserPhoto(res.getPhoto());
                        record.setCreateTime(new Date());
                        return record;

                    }).collect(Collectors.toList());

            iRoomHeartRecordService.saveBatch(list);
        }

        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .status(roomHeart.getStatus())
                .id(roomHeart.getId())
                .content(roomHeart.getContent())
                .stepName("自我介绍")
                .build();

        //发送聊天室属性里面存下当前游戏id以便主持操作
        messageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_ID, JSONObject.toJSONString(build),
                0, "", "");
        //发送聊天室属性 设置第一个人为

        AppRoomMaiUserResult result = appRoomMaiUserResults.get(0);
        result.setSayStatus(DynamicConstant.SayStatus.Pass);
        messageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MAI_SAY,
                JSONObject.toJSONString(result), 0, "", "");

        return roomHeart.getId();
    }

    @Override
    public boolean startSay(AppRoomWishCloseRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());

        String key = CacheKey.ROOM_MAI.getKey(String.valueOf(userId));
        String cacheKey = iRoomService.getRoomCacheKey(key, request.getRoomId(), userId);
        AppRoomMaiUserResult cache = iRoomService.verifyMai(request.getRoomId(), userId, cacheKey);
        cache.setSayStatus(DynamicConstant.SayStatus.Fan);
        CacheTemplate.setCache(cacheKey, cache, 1L, TimeUnit.DAYS);

        messageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MAI_SAY, JSONObject.toJSONString(cache), 0, "", "");
        return true;
    }

    int getRoomMaiIndex(Long uid, List<AppRoomMaiUserResult> appRoomMaiUserResults) {
        int i = -1;
        for (int k = 0; k < appRoomMaiUserResults.size(); k++) {
            if (uid.equals(appRoomMaiUserResults.get(k).getId())) {
                i = k;
                break;
            }
        }
        return i;
    }


    @Override
    public boolean overSay(AppRoomWishCloseRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        String key = CacheKey.ROOM_MAI.getKey(String.valueOf(userId));
        String cacheKey = iRoomService.getRoomCacheKey(key, request.getRoomId(), userId);
        AppRoomMaiUserResult cache = iRoomService.verifyMai(request.getRoomId(), userId, cacheKey);
        List<AppRoomMaiUserResult> appRoomMaiUserResults = iRoomService.maiUsers(request.getRoomId(), DynamicConstant.MaiType.MAI, false, true, 0L, 0);
        int i = getRoomMaiIndex(cache.getId(), appRoomMaiUserResults);
        cache.setSayStatus(DynamicConstant.SayStatus.Over);
        CacheTemplate.setCache(cacheKey, cache, 1L, TimeUnit.DAYS);
        messageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MAI_SAY, JSONObject.toJSONString(cache), 0, "", "");

        //结束后给下一个人开始发言 判断是不是最后一个人
        if (i != -1 && (i + 1) < appRoomMaiUserResults.size()) {
            AppRoomMaiUserResult result = appRoomMaiUserResults.get(i + 1);
            if (!CommonUtils.isNull(result)) {
                result.setSayStatus(DynamicConstant.SayStatus.Pass);
                messageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MAI_SAY,
                        JSONObject.toJSONString(result), 0, "", "");
            }
        }
        return true;
    }

    @Override
    public boolean selectHeart(AppRoomSelectHeartRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomHeart verify = verify(request.getRoomHeartId());

        R<AppUser> userInfo = remoteAppUserService.getUserInfo(request.getAimUserId(), SecurityConstants.APP);
        AppUser data = userInfo.getData();
        Assert.notNull(data, "您选择的对方不存在");

        String key = CacheKey.ROOM_MAI.getKey(String.valueOf(userId));
        String cacheKey = iRoomService.getRoomCacheKey(key, request.getRoomId(), userId);
        AppRoomMaiUserResult cache = iRoomService.verifyMai(request.getRoomId(), userId, cacheKey);

        String aimKey = CacheKey.ROOM_MAI.getKey(String.valueOf(request.getAimUserId()));
        String aimCacheKey = iRoomService.getRoomCacheKey(aimKey, request.getRoomId(), request.getAimUserId());
        AppRoomMaiUserResult aimCache = iRoomService.verifyMai(request.getRoomId(), request.getAimUserId(), aimCacheKey);

        AppRoomGameSelResult build = AppRoomGameSelResult.builder()
                .aimUserId(request.getAimUserId())
                .aimUserMaiNum(aimCache.getMaiNum())
                .userId(userId)
                .userMaiNum(cache.getMaiNum())
                .build();

        messageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_SEL, JSONObject.toJSONString(build), 0, "", "");

        return iRoomHeartRecordService.lambdaUpdate()
                .eq(RoomHeartRecord::getRoomHeartId, request.getRoomHeartId())
                .eq(RoomHeartRecord::getRoomId, request.getRoomId())
                .eq(RoomHeartRecord::getUserId, userId)
                .set(RoomHeartRecord::getAimUserId, request.getAimUserId())
                .set(RoomHeartRecord::getAimUserName, data.getNickName())
                .set(RoomHeartRecord::getAimUserPhoto, data.getPhoto())
                .update();
    }

    @Override
    public RoomHeart verify(Long id) {
        RoomHeart roomHeart = getById(id);
        Assert.notNull(roomHeart, "本场交友不存在");
        Assert.isTrue(!roomHeart.getStatus().equals(DynamicConstant.HeatStatus.END), "本场交友游戏已结束");
        return roomHeart;
    }

    @Override
    public AppRoomHeartSelResult selResult(AppRoomSelectHeartRequest request, Long userId) {
        iRoomService.verify(request.getRoomId());
        verify(request.getRoomHeartId());

        RoomHeartRecord one = iRoomHeartRecordService.lambdaQuery()
                .eq(RoomHeartRecord::getUserId, userId)
                .eq(RoomHeartRecord::getRoomId, request.getRoomId())
                .eq(RoomHeartRecord::getId, request.getRoomHeartId())
                .eq(RoomHeartRecord::getAimUserId, request.getAimUserId())
                .one();
        Assert.notNull(one, "没有您选择的目标");

        Optional<RoomHeartRecord> roomHeartRecord = iRoomHeartRecordService.lambdaQuery()
                .eq(RoomHeartRecord::getUserId, request.getAimUserId())
                .eq(RoomHeartRecord::getRoomId, request.getRoomId())
                .eq(RoomHeartRecord::getId, request.getRoomHeartId())
                .eq(RoomHeartRecord::getAimUserId, userId)
                .oneOpt();

        return AppRoomHeartSelResult.builder()
                .roomHeartId(request.getRoomHeartId())
                .roomId(request.getRoomId())
                .status(roomHeartRecord.isPresent() ? DynamicConstant.CheckStatus.YES : DynamicConstant.CheckStatus.NO)
                .build()
                ;
    }

    @Override
    public AppRoomHeartSelResult pubResult(AppRoomPubHeartRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomHeart verify = verify(request.getRoomHeartId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.YAN), "不是自由发言阶段");
        verify.setStatus(DynamicConstant.HeatStatus.GONG);
        updateById(verify);

        List<RoomHeartRecord> records = iRoomHeartRecordService.lambdaQuery()
                .eq(RoomHeartRecord::getRoomId, request.getRoomId())
                .eq(RoomHeartRecord::getRoomHeartId, request.getRoomHeartId())
                .list();

        Set<RoomHeartRecord> uniqueRecords = new HashSet<>();
        for (RoomHeartRecord record : records) {
            boolean isSpa = false;
            for (RoomHeartRecord one : uniqueRecords) {
                if (record.getAimUserId().equals(one.getUserId()) && record.getUserId().equals(one.getAimUserId())) {
                    isSpa = true;
                    record.setStatus(DynamicConstant.CheckStatus.YES);
                    record.setAimMaiNum(one.getMaiNum());
                    iRoomHeartRecordService.updateById(record);
                    one.setStatus(DynamicConstant.CheckStatus.YES);
                    one.setAimMaiNum(record.getMaiNum());
                    iRoomHeartRecordService.updateById(one);
                    break;
                }
            }
            if (!isSpa) {
                uniqueRecords.add(record);
            }
        }
        List<RoomHeartRecord> resultList = new ArrayList<>(uniqueRecords);

        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .content(verify.getContent())
                .id(verify.getId())
                .status(verify.getStatus())
                .list(resultList)
                .stepName("公布结果")
                .build();
        messageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_ID, JSONObject.toJSONString(build), 0, "", "");
        return AppRoomHeartSelResult.builder()
                .recordList(resultList)
                .status(resultList.isEmpty() ? DynamicConstant.CheckStatus.NO : DynamicConstant.CheckStatus.YES)
                .roomId(request.getRoomId())
                .roomHeartId(request.getRoomHeartId())
                .build()
                ;
    }

    @Override
    public void over(AppRoomPubHeartRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        Assert.isTrue(room.getUserId().equals(userId), "您无权限操作");
        RoomHeart verify = verify(request.getRoomHeartId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.GONG), "不是公布结果状态");
        verify.setStatus(DynamicConstant.HeatStatus.END);
        updateById(verify);

        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .content(verify.getContent())
                .id(0L)
                .status(verify.getStatus())
                .stepName("此次交友结束")
                .build();
        messageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_ID, JSONObject.toJSONString(build), 0, "", "");

        //TODO 匹配成功的下麦  匹配失败的留在位置上 成功的互相成为好友 并增加亲密度1000!
        List<RoomHeartRecord> listByStatus = iRoomHeartRecordService.getListByStatus(request.getRoomId(), request.getRoomHeartId(), DynamicConstant.CheckStatus.YES);
        String number = iParamService.selectConfigByKey(ParamConstant.HEAT_ADD_INTIMATE);
        for (RoomHeartRecord roomHeart : listByStatus) {
            String key = CacheKey.ROOM_MAI.getKey(String.valueOf(roomHeart.getUserId()));
            String cacheKey = key.replaceAll("\\{roomNumber}", String.valueOf(verify.getId()));
            AppRoomMaiUserResult result = CacheTemplate.getCache(cacheKey, AppRoomMaiUserResult.class);
            remoteAppUserService.setAttention(roomHeart.getUserId(), roomHeart.getAimUserId(), Long.valueOf(number), SecurityConstants.APP);
            if (!CommonUtils.isNull(result)) {
                messageService.sendCustomMessage(room.getUserId().toString(), room.getGroupId(),
                        RoomChatRoomKvConstant.RC_ALL_BROADCAST_MSG, result, RoomChatRoomKvConstant.XIA_MAI_MSG_TYPE);
            }
        }
    }

    @Override
    public AppRoomHeatResult findStatus(AppRoomHeartGetRequest request, Long userId) {
        if (request.getId().equals(0L)) return
                AppRoomHeatResult.builder()
                        .status(0)
                        .id(0L)
                        .build();
        RoomHeart verify = verify(request.getId());
        return AppRoomHeatResult.builder()
                .content(verify.getContent())
                .id(verify.getId())
                .status(verify.getStatus())
                .build()
                ;
    }

    @Override
    public void introOver(AppRoomPubHeartRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomHeart verify = verify(request.getRoomHeartId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.JISHAO), "不是自我介绍状态");
        verify.setStatus(DynamicConstant.HeatStatus.FAYAN);
        updateById(verify);

        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .content(verify.getContent())
                .id(verify.getId())
                .status(verify.getStatus())
                .stepName("自由发言")
                .build();
        messageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_ID, JSONObject.toJSONString(build), 0, "", "");


    }

    @Override
    public void makeOver(AppRoomPubHeartRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomHeart verify = verify(request.getRoomHeartId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.FAYAN), "不是自由发言状态");
        verify.setStatus(DynamicConstant.HeatStatus.SEL);
        updateById(verify);

        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .content(verify.getContent())
                .id(verify.getId())
                .status(verify.getStatus())
                .stepName("心动选择")
                .build();
        messageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_ID, JSONObject.toJSONString(build), 0, "", "");
    }

    @Override
    public void selOver(AppRoomPubHeartRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomHeart verify = verify(request.getRoomHeartId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.SEL), "不是心动选择状态");
        Long count = iRoomHeartRecordService
                .lambdaQuery()
                .eq(RoomHeartRecord::getRoomHeartId, request.getRoomHeartId())
                .eq(RoomHeartRecord::getAimUserId, 0L)
                .count();
        Assert.isTrue(count == 0, "还有玩家未选择");
        verify.setStatus(DynamicConstant.HeatStatus.YAN);
        updateById(verify);

        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .content(verify.getContent())
                .id(verify.getId())
                .status(verify.getStatus())
                .stepName("自由发言")
                .build();
        messageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_ID, JSONObject.toJSONString(build), 0, "", "");
    }

    @Override
    public void sendMessage(String chatRoomId, String userId) {


    }

    @Override
    public List<AppRoomGameSelResult> getResult(AppRoomHeartGetRequest request) {
        List<RoomHeartRecord> list = iRoomHeartRecordService
                .lambdaQuery()
                .eq(RoomHeartRecord::getRoomId, request.getRoomId())
                .eq(RoomHeartRecord::getRoomHeartId, request.getId())
                .ne(RoomHeartRecord::getAimUserId, 0L)
                .list();
        return list.stream().map(res -> {
            return AppRoomGameSelResult.builder()
                    .userId(res.getUserId())
                    .userMaiNum(res.getMaiNum())
                    .aimUserMaiNum(res.getAimMaiNum())
                    .aimUserId(res.getAimUserId())
                    .build();
        }).collect(Collectors.toList());
    }
}
